"""
 @time: 2019/6/6 16:07
 
 @Author: Unicorn
"""
import tensorflow as tf
import numpy as np

# 定义网络层
def add_layer(inputs, in_size, out_size, activation_function=None):
    """

    :param inputs:
    :param in_size:
    :param out_size:
    :param activation_function: 默认没有激活函数
    :return:
    """
    with tf.name_scope('layer'):
        with tf.name_scope('Weights'):
            Weights = tf.Variable(tf.random_normal([in_size, out_size]), name="W")
        with tf.name_scope('biases'):
            biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name="b")  # biases初始值不推荐为0,所以加上0.1
        with tf.name_scope('Wx_plus_b'):
            Wx_plus_b = tf.matmul(inputs, Weights) + biases
        if activation_function is None:
            outputs = Wx_plus_b
        else:
            outputs = activation_function(Wx_plus_b)
    return outputs


# linspace 取值范围是 (-1,1) ,生生300个实例,
x_data = np.linspace(-1, 1, 300)[:, np.newaxis]
noise = np.random.normal(0, 0.05, x_data.shape)
y_data = np.square(x_data) - 0.5 + noise

# 定义placeholder 输入层
with tf.name_scope('inputs'):
    xs = tf.placeholder(tf.float32, [None, 1], name="x_input")
    ys = tf.placeholder(tf.float32, [None, 1], name="y_input")  # None 表示不限定多少行数据,只指定列数 1

# 定义隐藏层,每层有10个神经元
layer1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)
# 将隐藏层的输出作为 预测层的输入,并经过激活函数
prediction = add_layer(layer1, 10, 1, activation_function=None)
# 计算损失和,进行参数优化
with tf.name_scope('loss'):
    loss = tf.reduce_mean(
        tf.reduce_sum(tf.square(ys - prediction), reduction_indices=[1]))  # reduction_indices 表示从列方向压缩累加
# 设置优化器,减小误差损失
with tf.name_scope('train_step'):
    train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

# 开启session会话
sess = tf.Session()
# 定义 tensorflow流程图框架 可视化 记录日志
writer = tf.summary.FileWriter("logs/", sess.graph)

sess.run(tf.global_variables_initializer())

# 训练1000次
for i in range(1000):
    sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
    if i % 20 == 0:
        prediction_value = sess.run(prediction, feed_dict={xs: x_data})


# close session
sess.close()
